package com.sttk.secreconeclick.bookkeep.fragment;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.viewmodel.CreationExtras;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.lzb.basic.utils.SPUtil;
import com.sttk.secreconeclick.bookkeep.BaseNoModelFragment;
import com.sttk.secreconeclick.bookkeep.Content;
import com.sttk.secreconeclick.bookkeep.R;
import com.sttk.secreconeclick.bookkeep.activity.AddBillActivity;
import com.sttk.secreconeclick.bookkeep.activity.ManageAccountBookActivity;
import com.sttk.secreconeclick.bookkeep.activity.SearchActivity;
import com.sttk.secreconeclick.bookkeep.activity.StatisticsActivity;
import com.sttk.secreconeclick.bookkeep.adapter.BillAdapter;
import com.sttk.secreconeclick.bookkeep.adapter.BillChildAdapter;
import com.sttk.secreconeclick.bookkeep.bean.AccountBookBean;
import com.sttk.secreconeclick.bookkeep.bean.BillBean;
import com.sttk.secreconeclick.bookkeep.bean.BillListBean;
import com.sttk.secreconeclick.bookkeep.databinding.ActivityHomeBinding;
import com.sttk.secreconeclick.bookkeep.databinding.FragmentHomeBinding;
import com.sttk.secreconeclick.bookkeep.dialog.ChangeCycleDialog;
import com.sttk.secreconeclick.bookkeep.dialog.SelMonthDialog;
import com.sttk.secreconeclick.bookkeep.dialog.SelYearDialog;
import com.sttk.secreconeclick.bookkeep.utils.AppSpUtils;
import com.sttk.secreconeclick.bookkeep.utils.MyBillReader;
import com.sztle.admodule.apiprocessor.OutRewardAdApi;
import com.sztle.admodule.apiprocessor.listener.IOutRewardCallback;

import java.text.SimpleDateFormat;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link HomeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HomeFragment extends BaseNoModelFragment<FragmentHomeBinding> implements View.OnClickListener, OnItemClickListener {

    private BillAdapter billAdapter;
    private int cyclePos;

    @Override
    protected int onCreate() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView() {
        mDataBinding.tvAccountBook.setOnClickListener(this);
        mDataBinding.llDate.setOnClickListener(this);
        mDataBinding.ivChange.setOnClickListener(this);
        mDataBinding.ivSearch.setOnClickListener(this);
        mDataBinding.tvReportStatistics.setOnClickListener(this);
        mDataBinding.ivAdd.setOnClickListener(this);

        mDataBinding.rvBillList.setLayoutManager(new LinearLayoutManager(mContext));
        billAdapter = new BillAdapter();
        mDataBinding.rvBillList.setAdapter(billAdapter);
        billAdapter.setOnItemClickListener(this);

    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.tvAccountBook) {//账本
            startActivity(ManageAccountBookActivity.class);
        } else if (id == R.id.llDate) {//日期
            if (cyclePos == 0) {
                showSelMonthDialog();
            } else if (cyclePos == 1) {
                showSelYearDialog();
            }
        } else if (id == R.id.ivChange) {//切换账单周期
            showChangeCycleDialog();
        } else if (id == R.id.ivSearch) {//搜索
            startActivity(SearchActivity.class);
        } else if (id == R.id.tvReportStatistics) {//报表统计
            OutRewardAdApi.showRewardAd(getActivity(), "report_statistics", new IOutRewardCallback() {
                @Override
                public void onRewardEnd() {
                    startActivity(StatisticsActivity.class);
                }
            });
        } else if (id == R.id.ivAdd) {//记账
            AddBillActivity.id = 0;
            startActivity(AddBillActivity.class);
        }
    }

    @Override
    public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (adapter instanceof BillChildAdapter) {
            BillChildAdapter billChildAdapter = (BillChildAdapter) adapter;
            BillBean item = billChildAdapter.getItem(position);
            AddBillActivity.id = item.getId();
            startActivity(AddBillActivity.class);
        }
    }

    @Override
    protected void initData() {

    }

    @Override
    public void onResume() {
        super.onResume();
        setData();
        setText();
        getData();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            setText();
            getData();
        }
    }

    private void setData() {
        cyclePos = SPUtil.getInt(mContext, Content.cycle, 0);
        mDataBinding.ivDate.setVisibility(View.VISIBLE);
        if (cyclePos == 0) {
            mDataBinding.tvDate.setText(TimeUtils.getNowString(new SimpleDateFormat("yyyy年M月")));
//            mDataBinding.tvExpenditureText.setText(getString(R.string.this_month_expenditure));
//            mDataBinding.tvIncomeText.setText(getString(R.string.this_month_income));
        } else if (cyclePos == 1) {
            mDataBinding.tvDate.setText(TimeUtils.getNowString(new SimpleDateFormat("yyyy年")));
//            mDataBinding.tvExpenditureText.setText(getString(R.string.this_year_expenditure));
//            mDataBinding.tvIncomeText.setText(getString(R.string.this_year_income));
        } else if (cyclePos == 2) {
            mDataBinding.tvDate.setText(getString(R.string.all_bill));
            mDataBinding.ivDate.setVisibility(View.GONE);
//            mDataBinding.tvExpenditureText.setText(getString(R.string.all_expenditure));
//            mDataBinding.tvIncomeText.setText(getString(R.string.all_income));
        }
    }

    private void setText() {
        String expenditure = "", income = "", balance = getString(R.string.total_balance);
        boolean isShowBalance = SPUtil.getBoolean(mContext, Content.showBalance, true);
        if (cyclePos == 0) {
            expenditure = getString(R.string.this_month_expenditure);
            income = getString(R.string.this_month_income);
            if (!isShowBalance) {
                balance = getString(R.string.this_month_balance);
            }
        } else if (cyclePos == 1) {
            expenditure = getString(R.string.this_year_expenditure);
            income = getString(R.string.this_year_income);
            if (!isShowBalance) {
                balance = getString(R.string.this_year_balance);
            }
        } else if (cyclePos == 2) {
            expenditure = getString(R.string.all_expenditure);
            income = getString(R.string.all_income);
        }
        int textPos = SPUtil.getInt(mContext, Content.indexText, 0);
        if (textPos == 0) {
            mDataBinding.tvExpenditureText.setText(expenditure);
            mDataBinding.tvIncomeText.setText(income);
            mDataBinding.tvBalanceText.setText(balance);
        } else if (textPos == 1) {
            mDataBinding.tvExpenditureText.setText(income);
            mDataBinding.tvIncomeText.setText(expenditure);
            mDataBinding.tvBalanceText.setText(balance);
        } else if (textPos == 2) {
            mDataBinding.tvExpenditureText.setText(balance);
            mDataBinding.tvIncomeText.setText(expenditure);
            mDataBinding.tvBalanceText.setText(income);
        }
    }

    private void getData() {
        int accountPos = SPUtil.getInt(mContext, Content.accountBook, 0);
        AccountBookBean accountBookBean = AppSpUtils.getAccountBookList().get(accountPos);
        List<BillListBean> listData = MyBillReader.getSortDate(accountBookBean.getBillBeanList(), mDataBinding.tvDate.getText().toString(), cyclePos);

        boolean isShowBalance = SPUtil.getBoolean(mContext, Content.showBalance, true);

        // 计算总收入、总支出和总结余
        double totalExpenditure = 0.0;
        double totalIncome = 0.0;
        double totalBalance = 0.0;

        if (isShowBalance) {
            for (BillBean billBean : accountBookBean.getBillBeanList()) {
                if (billBean.isIncome()) {
                    totalBalance += billBean.getMoney();
                } else {
                    totalBalance -= billBean.getMoney();
                }
            }
        }

        if (listData != null && listData.size() > 0) {
            for (BillListBean billListBean : listData) {
                totalExpenditure += billListBean.getExpenditure();
                totalIncome += billListBean.getIncome();
            }
            if (!isShowBalance) {
                totalBalance = totalIncome - totalExpenditure;
            }

            billAdapter.setList(listData);
            mDataBinding.rvBillList.setVisibility(View.VISIBLE);
            mDataBinding.tvBillNoData.setVisibility(View.GONE);
        } else {
            // 无数据时显示0
            totalExpenditure = 0.0;
            totalIncome = 0.0;
            totalBalance = 0.0;

            mDataBinding.rvBillList.setVisibility(View.GONE);
            mDataBinding.tvBillNoData.setVisibility(View.VISIBLE);
        }

        // 更新UI显示，保留两位小数
        int textPos = SPUtil.getInt(mContext, Content.indexText, 0);
        if (textPos == 0) {
            mDataBinding.tvExpenditure.setText(String.format("%.2f", totalExpenditure));
            mDataBinding.tvIncome.setText(String.format("%.2f", totalIncome));
            mDataBinding.tvTotalBalance.setText(String.format("%.2f", totalBalance));
        } else if (textPos == 1) {
            mDataBinding.tvExpenditure.setText(String.format("%.2f", totalIncome));
            mDataBinding.tvIncome.setText(String.format("%.2f", totalExpenditure));
            mDataBinding.tvTotalBalance.setText(String.format("%.2f", totalBalance));
        } else if (textPos == 2) {
            mDataBinding.tvExpenditure.setText(String.format("%.2f", totalBalance));
            mDataBinding.tvIncome.setText(String.format("%.2f", totalExpenditure));
            mDataBinding.tvTotalBalance.setText(String.format("%.2f", totalIncome));
        }
    }

    private void showSelMonthDialog() {
        SelMonthDialog dialog = new SelMonthDialog(mContext);
        dialog.setDate(mDataBinding.tvDate.getText().toString());
        dialog.setListener(new SelMonthDialog.Ilistener() {
            @Override
            public void clickConfirm(long date) {
                mDataBinding.tvDate.setText(TimeUtils.millis2String(date, new SimpleDateFormat("yyyy年M月")));
                getData();
            }
        });
        dialog.show();
    }

    private void showSelYearDialog() {
        SelYearDialog dialog = new SelYearDialog(mContext);
        dialog.setDate(mDataBinding.tvDate.getText().toString());
        dialog.setListener(new SelYearDialog.Ilistener() {
            @Override
            public void clickConfirm(long date) {
                mDataBinding.tvDate.setText(TimeUtils.millis2String(date, new SimpleDateFormat("yyyy年")));
                getData();
            }
        });
        dialog.show();
    }

    private void showChangeCycleDialog() {
        ChangeCycleDialog dialog = new ChangeCycleDialog(mContext);
        dialog.setListener(new ChangeCycleDialog.Ilistener() {
            @Override
            public void clickItem(int pos) {
                SPUtil.putInt(mContext, Content.cycle, pos);
                setData();
                setText();
                getData();
            }
        });
        dialog.show();
    }

}